# -*- coding: utf-8 -*-
from odoo import models, fields, api, _


class AccountReport(models.TransientModel):
    """ Here, we just define class fields.
    For methods, go more bottom at this file.

    The class hierarchy is :
    * AccountReport
    ** AccountReportProduct
    *** AccountReportProductItem
    """

    _name = 'report.invoice.xls'

    # Filters fields, used for data computation
    # need add a domain to filter customer invoice
    filter_invoice_line_ids = fields.Many2many('account.invoice.line')
    company_id = fields.Many2one('res.company')
    delivery_qty_sum = fields.Float(digits=(16, 2))
    amount_sum = fields.Float(digits=(16, 2))

    # Data fields, used to browse report data
    product_ids = fields.One2many(
        comodel_name='report.invoice.xls.product',
        inverse_name='report_id'
    )


class AccountReportProduct(models.TransientModel):

    _name = 'report.invoice.xls.product'
    _order = 'amount_sum DESC'

    report_id = fields.Many2one(
        'report.invoice.xls',
        ondelete='cascade',
        index=True
    )

    # Data fields, used to keep link with real object
    product_id = fields.Many2one(
        'product.product',
        index=True
    )

    product_name = fields.Char()
    delivery_qty_sum = fields.Float(digits=(16, 2))
    amount_sum = fields.Float(digits=(16, 2))

    product_item_ids = fields.One2many(
        comodel_name='report.invoice.xls.product.item',
        inverse_name='report_product_id'
    )


class AccountReportProductItem(models.TransientModel):

    _name = 'report.invoice.xls.product.item'
    _order = 'date DESC'

    report_product_id = fields.Many2one(
        comodel_name='report.invoice.xls.product',
        ondelete='cascade',
        index=True
    )

    # Data fields, used to keep link with real object
    invoice_line_id = fields.Many2one('account.invoice.line')

    # Data fields, used for report display
    date = fields.Date(default=lambda self: fields.Date.today())
    product_name = fields.Char()
    so = fields.Char()
    customer_so = fields.Char()
    category_name = fields.Char()
    invoice_name = fields.Char()
    customer_product_name = fields.Char()
    customer_product_code = fields.Char()
    delivered_qty = fields.Float()
    uom = fields.Char()
    curr_name = fields.Char()
    net_length = fields.Float()
    price_unit = fields.Float()
    amount = fields.Float()
    force_date = fields.Char()
    deliver_order = fields.Char()


class InvoiceItemsReportCompute(models.TransientModel):
    """ Here, we just define methods.
    For class fields, go more top at this file.
    """

    _inherit = 'report.invoice.xls'

    @api.multi
    def print_report(self, xlsx_report=True):
        self.ensure_one()
        self.compute_data_for_report()
        report_name = 'account_invoice_extend.report_invoice_items_xlsx'
        return self.env['report'].get_action(docids=self.ids, report_name=report_name)

    @api.multi
    def print_customer_report(self, xlsx_report=True):
        self.ensure_one()
        self.compute_data_for_report()
        report_name = 'account_invoice_extend.report_invoice_items_customer_xlsx'
        return self.env['report'].get_action(docids=self.ids, report_name=report_name)

    @api.multi
    def compute_data_for_report(self):
        self.ensure_one()
        self.filter_invoice_line_ids.update({'is_export_xls': True})
        invoice_line = self.env['account.invoice.line'].browse(self.filter_invoice_line_ids.ids)
        product_ids = invoice_line.mapped('product_id')
        mast = self.env['report.invoice.xls.product']
        detl = self.env['report.invoice.xls.product.item']
        # deposit_product_id = self.env['ir.values'].get_default('sale.config.settings', 'deposit_product_id_setting')
        for product in product_ids:
            # ignore deposit item
            # if product.id == deposit_product_id:
            #     continue
            delivery_qty_sum = 0
            all_inv = invoice_line.filtered(lambda l: l.product_id == product)
            for i in all_inv:
                # delivery_qty_sum += sum(i.sale_line_ids.mapped('qty_delivered'))
                delivery_qty_sum += i.quantity
            mast_id = mast.create({
                'report_id': self.id,
                'product_id': product.id,
                'product_name': product.display_name,
                'delivery_qty_sum': delivery_qty_sum,
                'amount_sum': sum(
                    # invoice_line.filtered(lambda l: l.product_id == product).mapped('price_subtotal')),
                    invoice_line.filtered(lambda l: l.product_id == product).mapped('amount_total')),
            })
            invs = invoice_line.filtered(lambda l: l.product_id == product)
            for inv in invs:
                pcn = self.env["product.customer.name"].search([('partner_id', '=', inv.partner_id.id), ('product_id', '=', inv.product_id.id)])
                detl.create({
                    'report_product_id': mast_id.id,
                    'invoice_line_id': inv.id,
                    'date': inv.invoice_id.create_date,
                    'invoice_name': inv.invoice_id.number,
                    'product_name': inv.product_id.display_name,
                    'so': inv.origin,
                    'net_length': inv.net_length,
                    'customer_so': inv.sale_line_ids and inv.sale_line_ids[0].order_id.client_order_ref or False,
                    'category_name': inv.product_id.class_code1,
                    'customer_product_code': pcn and pcn.product_customer_code or False,
                    'customer_product_name': pcn and pcn.product_customer_name or False,
                    'force_date': inv.invoice_id.force_date,
                    'deliver_order': inv.invoice_id.deliver_order,
                    # 'delivered_qty': sum(inv.sale_line_ids.mapped('qty_delivered')),
                    'delivered_qty': inv.quantity,
                    'uom': inv.uom_id.name,
                    'curr_name': inv.currency_id.name,
                    'price_unit': inv.price_unit,
                    'amount': inv.amount_total
                })
        self.update({
            'delivery_qty_sum': sum(self.product_ids.mapped('delivery_qty_sum')),
            'amount_sum': sum(self.product_ids.mapped('amount_sum'))
        })
